package me.kafeitu.demo.activiti.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import me.kafeitu.demo.activiti.util.UserUtil;

import org.flowable.engine.IdentityService;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.tanghom.support.utils.Md5Util;

/**
 * 内部登录页面，绕开shiro，这里面登录的用户是activiti user
 *
 * @author HenryYan
 */
@Controller
@RequestMapping("/user")
public class UserLoginController {
	
	private static Logger logger = LoggerFactory.getLogger(UserLoginController.class);

	// Flowable Identify Service
	@Autowired
	private IdentityService identityService;


    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    

    /**
     * 登录系统
     *
     * @param userName
     * @param password
     * @param session
     * @return
     */
    @RequestMapping(value = "/logon",method = RequestMethod.POST)
    public String logon(@RequestParam("username") String userName, @RequestParam("password") String password, HttpSession session) {
        logger.debug("logon request: {username={}, password={}}", userName, password);
        password = Md5Util.encrypt(password);
        long exist = identityService.createUserQuery().userId(userName).count();
        boolean checkPassword = identityService.checkPassword(userName, password);
        if (exist==1 || checkPassword) {

            // read user from database
            User user = identityService.createUserQuery().userId(userName).singleResult();
            UserUtil.saveUserToSession(session, user);

            List<Group> groupList = identityService.createGroupQuery().groupMember(userName).list();
            session.setAttribute("groups", groupList);

            String[] groupNames = new String[groupList.size()];
            for (int i = 0; i < groupNames.length; i++) {
                System.out.println(groupList.get(i).getName());
                groupNames[i] = groupList.get(i).getName();
            }

            session.setAttribute("groupNames", ArrayUtils.toString(groupNames));

            return "redirect:/demo/index";
        } else {
            return "redirect:/user/login?error=true";
        }
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
    	UserUtil.logout(session);
        return "redirect:/user/login";
    }
}
